using Microsoft.AspNetCore.Mvc;
using System.Text;
using System.Text.Json;
using System.Security.Cryptography;

namespace SG3L_RAG.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ImageAnalysisController : ControllerBase
    {
        private readonly ILogger<ImageAnalysisController> _logger;
        private readonly HttpClient _httpClient;
        
        // 百度OCR配置（需要在appsettings.json中配置）
        private readonly string _apiKey;
        private readonly string _secretKey;
        private readonly string _baiduOcrUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";

        public ImageAnalysisController(ILogger<ImageAnalysisController> logger, HttpClient httpClient, IConfiguration configuration)
        {
            _logger = logger;
            _httpClient = httpClient;
            _apiKey = configuration["BaiduOCR:ApiKey"] ?? "";
            _secretKey = configuration["BaiduOCR:SecretKey"] ?? "";
        }

        /// <summary>
        /// 从图片中提取文字 (OCR)
        /// </summary>
        /// <param name="image">图片文件</param>
        /// <returns>提取的文字内容</returns>
        [HttpPost("extract-text")]
        public async Task<IActionResult> ExtractTextFromImage(IFormFile image)
        {
            try
            {
                if (image == null || image.Length == 0)
                {
                    return BadRequest(new { message = "请上传图片文件" });
                }

                // 验证文件类型
                var allowedTypes = new[] { "image/jpeg", "image/jpg", "image/png", "image/bmp" };
                if (!allowedTypes.Contains(image.ContentType.ToLower()))
                {
                    return BadRequest(new { message = "不支持的图片格式，请上传 JPG、PNG 或 BMP 格式的图片" });
                }

                // 验证文件大小 (最大4MB)
                if (image.Length > 4 * 1024 * 1024)
                {
                    return BadRequest(new { message = "图片文件大小不能超过4MB" });
                }

                // 获取访问令牌
                var accessToken = await GetBaiduAccessToken();
                if (string.IsNullOrEmpty(accessToken))
                {
                    return StatusCode(500, new { message = "获取百度API访问令牌失败" });
                }

                // 调用百度OCR API
                var extractedText = await CallBaiduOCR(image, accessToken);
                
                _logger.LogInformation($"成功提取图片文字，文件: {image.FileName}, 提取文字长度: {extractedText.Length}");

                return Ok(new 
                { 
                    success = true,
                    message = "文字提取成功",
                    data = new
                    {
                        fileName = image.FileName,
                        fileSize = image.Length,
                        extractedText = extractedText,
                        textLength = extractedText.Length
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"图片文字提取失败: {ex.Message}");
                return StatusCode(500, new { message = $"图片文字提取失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取百度API访问令牌
        /// </summary>
        private async Task<string> GetBaiduAccessToken()
        {
            try
            {
                if (string.IsNullOrEmpty(_apiKey) || string.IsNullOrEmpty(_secretKey))
                {
                    _logger.LogError("百度OCR API Key 或 Secret Key 未配置");
                    return "";
                }

                var tokenUrl = $"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={_apiKey}&client_secret={_secretKey}";
                
                var response = await _httpClient.GetAsync(tokenUrl);
                var content = await response.Content.ReadAsStringAsync();
                
                if (response.IsSuccessStatusCode)
                {
                    var tokenResponse = JsonSerializer.Deserialize<JsonElement>(content);
                    if (tokenResponse.TryGetProperty("access_token", out var token))
                    {
                        return token.GetString() ?? "";
                    }
                }
                
                _logger.LogError($"获取百度访问令牌失败: {content}");
                return "";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取百度访问令牌异常");
                return "";
            }
        }

        /// <summary>
        /// 调用百度OCR API
        /// </summary>
        private async Task<string> CallBaiduOCR(IFormFile image, string accessToken)
        {
            try
            {
                // 将图片转换为Base64
                byte[] imageBytes;
                using (var memoryStream = new MemoryStream())
                {
                    await image.CopyToAsync(memoryStream);
                    imageBytes = memoryStream.ToArray();
                }
                var base64Image = Convert.ToBase64String(imageBytes);

                // 构建请求参数
                var requestData = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("image", base64Image),
                    new KeyValuePair<string, string>("language_type", "CHN_ENG"), // 中英文混合
                    new KeyValuePair<string, string>("detect_direction", "true"), // 检测图像朝向
                    new KeyValuePair<string, string>("paragraph", "false"), // 是否输出段落信息
                    new KeyValuePair<string, string>("probability", "false") // 是否返回识别结果中每一行的置信度
                };

                var formContent = new FormUrlEncodedContent(requestData);
                
                // 发送请求
                var requestUrl = $"{_baiduOcrUrl}?access_token={accessToken}";
                var response = await _httpClient.PostAsync(requestUrl, formContent);
                var content = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    var ocrResponse = JsonSerializer.Deserialize<JsonElement>(content);
                    
                    if (ocrResponse.TryGetProperty("words_result", out var wordsResult))
                    {
                        var extractedLines = new List<string>();
                        
                        foreach (var word in wordsResult.EnumerateArray())
                        {
                            if (word.TryGetProperty("words", out var wordsText))
                            {
                                var text = wordsText.GetString();
                                if (!string.IsNullOrWhiteSpace(text))
                                {
                                    extractedLines.Add(text.Trim());
                                }
                            }
                        }
                        
                        return string.Join("\n", extractedLines);
                    }
                }
                else
                {
                    _logger.LogError($"百度OCR API调用失败: {content}");
                    throw new Exception($"OCR识别失败: {content}");
                }

                return "";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "调用百度OCR API异常");
                throw;
            }
        }

        /// <summary>
        /// 健康检查
        /// </summary>
        [HttpGet("health")]
        public IActionResult Health()
        {
            return Ok(new 
            { 
                service = "ImageAnalysis OCR",
                status = "healthy",
                timestamp = DateTime.UtcNow,
                apiConfigured = !string.IsNullOrEmpty(_apiKey) && !string.IsNullOrEmpty(_secretKey)
            });
        }
    }
}
